$(function() {

	refresh();
});
function refresh() {
	if (window.errorMsg) {
		$("#alert-warning").html(window.errorMsg).removeClass("hidden").hide().fadeIn("slow");
		$("#alert-warning").fadeOut(5000);
	}
	validationOption = {
		rules : {
			username : {
				minlength : 2,
				maxlength : 20,
				required : true
			},
			nickname : {
				minlength : 2,
				maxlength : 20,
				required : true
			},
			roleName : {
				required : true
			}
		},
		messages : {
			username : {
				minlength : "用户名应多于2个字母！",
				maxlength : "用户名应少于20个字母！",
				required : "请填写用户名！"
			},
			nickname : {
				minlength : "昵称应多于2个字母！",
				maxlength : "昵称应少于20个字母！",
				required : "请填写昵称！"
			},
			roleName : {
				required : "请选择角色！"
			}
		},
		highlight : function(element) {
			$(element).closest('.form-group').addClass('has-error');
		},
		unhighlight : function(element) {
			$(element).closest('.form-group').removeClass('has-error');
		},
		errorElement : 'span',
		errorClass : 'help-block',
		errorPlacement : function(error, element) {
			if (element.parent('.input-group').length) {
				error.insertAfter(element.parent());
			} else {
				error.insertAfter(element);
			}
		}

	};
	$('#addForm').validate(validationOption);
	$('#editForm').validate(validationOption);
	var mytable = $('#user')
			.DataTable(
					{
						"processing" : true,
						"serverSide" : true,
						"dom" : '<"top"f>tr<"bottom"ip>',
						// "deferRender" : true,
						"order" : [ [ 2, "desc" ] ],
						"stateSave" : true,
						"ajax" : {
							"url" : window.basePath + "user/list",
							"type" : "POST"
						},
						"language" : {
							"zeroRecords" : "无数据！",
							"infoEmpty" : "没有找到该条记录！",
							"infoFiltered" : "(共 _MAX_ 条记录)",
							"processing" : "加载中...",
							"lengthMenu" : "_MENU_ Einträge anzeigen",
							"info" : "显示第_START_ 到第 _END_条记录 （共 _TOTAL_ 条记录）",
							"infoPostFix" : "",
							"search" : "搜索:  ",
							"paginate" : {
								"first" : "第一页",
								"previous" : "上一页",
								"next" : "下一页",
								"last" : "最后一页"
							}
						},
						"columnDefs" : [
								{
									"targets" : [ 0 ],
									"visible" : false,
								},
								{
									"targets" : [ 1 ],
								},
								{
									"targets" : [ 2 ],
								},
								{
									"targets" : [ 3 ],
								},
								{
									"targets" : [ 4 ],
								},
								{
									"targets" : -1,
									"data" : null,
									"orderable" : false,
									"defaultContent" : "<button type='button' class='btn btn-success btn-sm'>编辑</button>&nbsp;<button type='button' class='btn btn-danger btn-sm'>删除</button>&nbsp;<button type='button' class='btn btn-warning btn-sm'>重置</button>",
									"render" : function(data, type, row) {
										if (row[4] == 'PM') {
											return "<button type='button' class='btn btn-success btn-sm'>编辑</button>&nbsp;<button type='button' class='btn btn-danger btn-sm'>删除</button>&nbsp;<button type='button' class='btn btn-warning btn-sm'>重置</button>&nbsp;<button type='button' class='btn btn-info btn-sm'>赋权限</button>";
										}
									},
								} ],
					});
	$.fn.dataTable.ext.errMode = 'throw';
	$("#user tbody").on("click", "button", function() {
		var data = mytable.row($(this).parents('tr')).data();
		if ($(this).hasClass('btn-success')) {
			showEditModal(data[0]);
		} else if ($(this).hasClass('btn-danger')) {
			showDeleteModal(data[0]);
		} else if ($(this).hasClass('btn-info')) {
			showControlModal(data[0]);
		} else if ($(this).hasClass('btn-warning')) {
			showResetModal(data[0]);
		}
	});
	loadRoles();
	$("#addUser").click(function() {
		$("#createUserModal").modal('show');
		
	});

}
function showDeleteModal(id) {
	$("#idD").val(id);
	$('#deleteUserModal').modal('show');
}
function showResetModal(id) {
	$("#idR").val(id);
	$('#resetUserModal').modal('show');
}

function showEditModal(id) {
	target = window.basePath + "user/find/" + id;
	$.ajax({
		url : target,
		success : function(data) {
			$("#idE").val(data.id);
			$("#usernameE").val(data.username);
			$("#nicknameE").val(data.nickname);
			$("#edit-menu li a").each(function(index) {
				dataValue = $(this).attr("dataValue");
				if (dataValue == data.roleId) {
					$("#editDropDownBtn").text(data.roleName).append('<span class="caret"></span>');
					$("#roleIdE").val(data.roleId);
				}
			});
			$('#editUserModal').modal('show');
		}
	});

}

function showControlModal(id) {
	$("#userIdControl").val(id);
	$.ajax({
		url : window.basePath + "user/getProject",
		data : {
			'id' : id
		},
		type : 'POST',
		success : function(data) {
			if (data != null) {
				var tree = $("#tree").dynatree("getTree");
				var projectIds = new Array();
				var projectNames = new Array();
				for (var i = 0; i < data.length; i++) {
					tree.selectKey(data[i].id, true);
					projectIds.push(data[i].id);
					projectNames.push(data[i].name);
				}
				$("#projectId").val(projectIds.join(","));
				$("#projectName").val(projectNames.join(","));
			} else {
				$("#tree").dynatree("getRoot").visit(function(node) {
					node.select(false);
				});

				$("#projectId").val("");
				$("#projectName").val("");
			}

		}
	});
	$('#controlUserModal').modal('show');
}
function loadRoles() {
	target = window.basePath + "role/list";
	$.ajax({
		url : target,
		success : function(data) {
			menus = $(".dropdown-menu.user");
			options = "";
			for (var i = 0; i < data.length; i++) {
				options += "<li role='presentation'><a role='menuitem' dataValue='" + data[i].id
						+ "' tabindex='-1' href='#' data-toggle='dropdown'>" + data[i].role + "</option>";
			}
			menus.empty();
			$(".dropdown-menu.user").append(options);
			target = $("#add-menu li a:eq(0)");
			$("#addDropDownBtn").text(target.text() + " ").append('<span class="caret"></span>');
			$("#roleId").val(target.attr("dataValue"));
			$("#add-menu li a").click(function() {
				$('#roleId').val($(this).attr("dataValue"));
				$("#addDropDownBtn").text($(this).text() + " ").append('<span class="caret"></span>');
			});

			$("#edit-menu li a").click(function() {
				$('#roleIdE').val($(this).attr("dataValue"));
				$("#editDropDownBtn").text($(this).text() + " ").append('<span class="caret"></span>');
			});

		}
	});

	$("#tree").dynatree({
		checkbox : true,
		selectMode : 3,
		onPostInit : function(isReloading, isError) {
			this.reactivate();
		},
		onSelect : function(select, node) {
			// Get a list of all selected nodes, and convert
			// to a key array:
			var selKeys = $.map(node.tree.getSelectedNodes(), function(node) {
				if (!node.data.isFolder) {
					return node.data.key;
				}
			});
			$("#projectId").val(selKeys.join(","));
			var selTitles = $.map(node.tree.getSelectedNodes(), function(node) {
				if (!node.data.isFolder) {
					return node.getParent().getParent().data.title + node.getParent().data.title + node.data.title;
				}
			});
			$("#projectName").val(selTitles.join(", "));
		},
		onDblClick : function(node, event) {
			node.toggleSelect();
		},
		onKeydown : function(node, event) {
			if (event.which == 32) {
				node.toggleSelect();
				return false;
			}
		},
		initAjax : {
			url : window.basePath + "project/loadProject"
		}
	});
}